﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DxfFilesScan
{
    public class DxfComparer
    {
        private string currentDir;
        private string lastFull;
        private string addedFull;
        private string removedFull;
        public DxfComparer(string currentDir, string lastDir)
        {
            this.currentDir = currentDir;
            lastFull = Path.Combine(lastDir, "last.txt");
            addedFull = Path.Combine(lastDir, "added.txt");
            removedFull = Path.Combine(lastDir, "removed.txt");
        }



        public void Compare2StringLists(IList<string> current, IList<string> last, out IList<string> added, out IList<string> removed)
        {
            HashSet<string> setCurrent = new HashSet<string>(current);
            HashSet<string> setLast = new HashSet<string>(last);
            added = setCurrent.Except(setLast).ToList();
            removed = setLast.Except(setCurrent).ToList();
        }

        private IList<string> ScanDxfInfos()
        {
            string[] currentFiles = Directory.GetFiles(currentDir, "*.dxf", SearchOption.AllDirectories);
            return currentFiles.Select(x => new DxfInfo(currentDir, x).ToString()).ToList();
        }

        public void CompareCurrentDirWithLastFile(bool autoUpdate, out IList<string> added, out IList<string> removed)
        {
            IList<string> currents = ScanDxfInfos();
            IList<string> lasts;

            if (File.Exists(lastFull))
            {
                lasts = File.ReadAllLines(lastFull);
                Compare2StringLists(currents, lasts, out added, out removed);
                if (autoUpdate)
                {
                    File.WriteAllLines(lastFull, currents);
                    if (added.Any())
                        File.WriteAllLines(addedFull, added);
                    if (removed.Any())
                        File.WriteAllLines(removedFull, removed);
                }

            }
            else
            {
                File.WriteAllLines(lastFull, currents);
                added = new string[] { };
                removed = new string[] { };
            }

        }

    }
}
